<?php
/**
 * 缓存组件
 *
 * @author seraph.liujb 2009.8.10
 */

class Common_Cache
{
	/**
	 * 初始化缓存配置，返回Zend_Cache_Core实例
	 *
	 * @param $cacheType 需要调用的cache类型，默认为memcache
	 * @return Zend_Cache_Core
	 */
	public static function factory($type = 'memcache')
	{
		$self = new self();
		$functionName = '_' . $type;
		return $self->$functionName();
	}

	/**
	 * _memcache
	 * @return Zend_Cache_Core
	 */
	private function _memcache()
	{
		//获取配置参数
		$params = $this->getConfig('memcache');

		$fo = array(
   			'lifeTime' => 7200,
   			'automatic_serialization' => true,
		);
		$bo = array(
	   		'servers'=>array(
				array(
		   			'host'=>$params['host'],
		   			'port'=>$params['port'],
		   			'persistent'=>true,
					//'weight'=>1,
					//'timeout'=>5,
					//'retry_interval'=>15,
					//'status'=>true,
				),
			),
			'compression'=>true,
		);
		$cache = Zend_Cache::factory('Core','Memcached',$fo,$bo);
		return $cache;
	}

	/**
	 * _file
	 * @return Zend_Cache_Core
	 */
	private function _file()
	{
		//获取配置参数
		$params = $this->getConfig('filecache');

		$fo = array(
   			'lifeTime' => 7200,
   			'automatic_serialization' => true,
		);
		$bo = array('cache_dir' => APPLICATION_PATH . $params['dir']);
		$cache = Zend_Cache::factory('Core','File',$fo,$bo);
		return $cache;
	}

	/**
	 * 读取指定类型数据库配置文件
	 * @param  string $type memcache filecache
	 * @return array
	 * host 主机
	 * port 端口
	 * dir 缓存目录
	 */
	public static function getConfig($type)
	{
		$config = new Zend_Config_Ini(APPLICATION_PATH . '/_config/system.ini',$type);
		if ($config instanceof Zend_Config) {
			$config = $config->toArray();
		}
		return $config;
	}
}
